package file;

import image.PixelArray;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author Jaan Lambert
 * Class reading and writing files.
 */
public class FileManipulator {
	
	FileReader fr = null;
	BufferedReader br = null;
	
	public boolean readFileToPixelArray (PixelArray pixels, String fileName) {
		createReader(fileName);
		String fileLine = null;
		int currentNumber;
		int lineNumber = 0;
		try {
			// Reading file and saving results to array.
			while((fileLine = br.readLine()) != null) {
				if (!pixels.isWidthSet()) {
					pixels.setWidth(fileLine.length());
				}
				for(int i = 0; i < fileLine.length(); i++) {
					currentNumber = Integer.parseInt(fileLine.substring(i,i + 1));
					if (currentNumber != 0) {
						pixels.add(i, lineNumber, currentNumber);
					}
				}
				
				lineNumber++;
			}
			
			pixels.setHeight(lineNumber);
			// Closing stream
			br.close();
			
		} catch (NumberFormatException e) {
			System.err.println("In file in wrong format " + e.getMessage());
		} catch (IOException e) {
			System.err.println("IOException: " + e.getMessage());
		}
		return true;
		
	}
	
	public boolean createReader(String fileName) {
		try {
			fr = new FileReader(fileName);
			br = new BufferedReader(fr);
		} catch (FileNotFoundException e) {
			System.err.println("File does not exist: " + e.getMessage());
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
